<?php

namespace app\common\model;

use app\common\lib\ZhyxMongo;
use app\common\model\Followtask as FollowtaskModel;
use catcher\exceptions\FailedException;
use MongoDB\BSON\ObjectId;
use MongoDB\BSON\UTCDateTime;

class FollowPushQuestionnaire extends BaseModel
{
    protected $name = "follow_push_questionnaire";

    /**
     * 统计随访表单报表
     *
     * @param array $condition 查询条件
     * @return array
     */
    public function getFollowFormList(array $condition=[]): array
    {
        $paramArr = ["dept_id" => "dept_id", "task_id" => "task_id", "projectName" => "projectName", "created_ymd" => "create_date"];

        $match = [];
        foreach($paramArr as $k => $v){
            if(isset($condition[$k]) && !empty($condition[$k]) && $condition[$k]!==""){
                if($k==="projectName"){
                    $match[$v] = ['$regex' => $condition[$k]];
                }elseif($k==="created_ymd"){
                    $match[$v] = ['$gte' => $condition[$k][0], '$lte' => $condition[$k][1]];
                }else{
                    $match[$v] = is_string($condition[$k])?trim($condition[$k]):(int)$condition[$k];
                }
            }
        }

        if(empty($match)){
            throw new FailedException('请至少传入一个条件作为查询');
        }

        $pip = [['$match' => $match], ['$group' => ['_id' => '$task_id', 'task_id' => ['$first' => '$task_id'], 'taskname' => ['$first' => '$taskname'], 'projectName' => ['$first' => '$projectName'], 'creator_name' => ['$first' => '$creator_name'], 'creator_dept_name' => ['$first' => '$creator_dept_name'], 'project_id' => ['$first' => '$project_id'], 'projectId' => ['$first' => '$projectId'], 'parentId' => ['$first' => '$parentId'], 'created_at' => ['$first' => '$created_at']]],['$sort' => ['created_at' => -1]]];

        $rets = ZhyxMongo::getInstance()->setCollection($this->name)->aggregate($pip);

        $arr = [];
        foreach ($rets as $k => $v) {
            $arr[] = (array)$v;
        }
        return $arr;
    }
}